<?php

namespace app\admin\controller\kuerp;

use app\common\controller\Backend;
use app\admin\model\kuerp\SaleGoalsDetail;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use \app\admin\model\department\Department as DepartmentModel;
use fast\Tree;
use think\Db;
use Exception;
/**
 * 业绩目标管理
 *
 * @icon fa fa-circle-o
 */
class SaleGoals extends Backend
{

    /**
     * SaleGoals模型对象
     * @var \app\admin\model\kuerp\SaleGoals
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\kuerp\SaleGoals;
        $this->view->assign("statusList", $this->model->getStatusList());
        $modelList = $this->model->getModelClassList();
        $this->view->assign("modelList", $modelList);
        $this->assignconfig("modelList", $modelList);
        //获取目标详情最早的年份
        $min_year = SaleGoalsDetail::min('year');
        $min_year = $min_year && $min_year < date('Y') ? $min_year : date('Y') - 3;
        $max_year = (int)date('Y') + 5;
        $yearlist = [];
        for ($i=$min_year; $i <= $max_year; $i++) { 
            $yearlist[$i] = $i;
        }
        $this->view->assign("yearlist", $yearlist);
        $this->assignconfig("yearlist", $yearlist);
        
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','years','model_class','status','createtime']);
                
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success('添加成功', '', '',['need_url' => true, 'id' => $this->model->id]);
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('编辑成功', '',['need_url' => true, 'id' => $row->id]);
    }

    public function editdetail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $year = $this->request->request('year');
        if (!$year) {
            $year = $row['years'][0];
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('data/a');
            foreach ($params as $k => $v) {
                $params[$k]['yeartarget'] = (float)$v['month_1'] + (float)$v['month_2'] + (float)$v['month_3'] + (float)$v['month_4'] + (float)$v['month_5'] + (float)$v['month_6'] + (float)$v['month_7'] + (float)$v['month_8'] + (float)$v['month_9'] + (float)$v['month_10'] + (float)$v['month_11'] + (float)$v['month_12'];
            }
            $result = false;
            Db::startTrans();
            try {
                //是否采用模型验证
                // if ($this->modelValidate) {
                //     $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                //     $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                //     $row->validateFailException()->validate($validate);
                // }
                $result = (new SaleGoalsDetail())->saveAll($params);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (false === $result) {
                $this->error(__('No rows were updated'));
            }
            $this->success('编辑成功');
        }
        $allDepartment = \app\admin\model\department\Admin::getAllDepartmentsArray($this->auth->id, true);
        $allDepartment = collection($allDepartment)->toArray();
        $departmentList = [];
        $adminList = Db::name('admin')->column('nickname', 'id');
        $department_adminids = [];
        if ($allDepartment) {
            $departmentids = array_column($allDepartment, 'id');
            $department_adminids = \app\admin\model\department\Admin::getDepartmentGroupAdminIds($departmentids);
        }
        foreach ($allDepartment as $k => $v) {
            $state = ['opened' => $v['parent_id'] ? false : true];
            $departmentList[] = [
                'id' => $v['id'],
                'type' => 'department',
                'parent' => $v['parent_id'] ? $v['parent_id'] : '#',
                'text' =>preg_replace('/&nbsp;|\s*|│|└|├\s*/','',__($v['name'])),//str_replace("&nbsp;",'', __($v['name'])) ,
                'state' => $state
            ];
        }
        $this->assignconfig('departmentnames', array_column($departmentList, 'text', 'id'));
        foreach ($allDepartment as $k => $v) {
            //获取部门员工
            if (!empty($department_adminids[$v['id']])) {
                $adminids = explode(',', $department_adminids[$v['id']]);
                foreach ($adminids as $k1 => $v1) {
                    $departmentList[] = [
                        'id' => 'admin_'.$v1,
                        'type' => 'user',
                        'icon' => 'string',
                        'parent' => $v['id'],
                        'text' => $adminList[$v1],
                        'state' => ['opened' => false]
                    ];
                }
            }
        }
        $this->assignconfig('adminList', $adminList);
        if (false === $this->request->isPost()) {
            $this->assignconfig('departmentList', $departmentList);
            $this->view->assign('row', $row);
            $this->assignconfig('id', $ids);
            $this->assignconfig('year', $year);
            return $this->view->fetch();
        }


    }

    public function detail_list()
    {
        $id = $this->request->request('id');
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $year = $this->request->request('year/d');
        $department_id = $this->request->request('department_id/d');
        $admin_id = $this->request->request('admin_id/d');
        if (!$year) {
            $year = $row['years'][0];
        }
        $department_ids = [];
        $admin_ids = [];
        if (!empty($admin_id)) {
            $where = [
                'salegoal_id' => $id,
                'year' => $year,
                'admin_id' => $admin_id
            ];
            $details = SaleGoalsDetail::where($where)->select();
            $admin_ids[] = $admin_id;
        } else {
            //获取直属下级部门及员工
            $department_ids = Db::name('department')->where(['parent_id' => $department_id, 'status' => 'normal'])->order('weigh desc,id desc')->column('id');
            array_unshift($department_ids, $department_id);
            $admin_ids = Db::name('department_admin')->where(['department_id' => $department_id])->column('admin_id');
            $where = [
                'salegoal_id' => $id,
                'year' => $year
            ];
            $details = SaleGoalsDetail::where($where)
            ->where(function($query) use($department_ids, $admin_ids) {
                $query->whereOr(function($query) use($department_ids) {
                    $query->whereIn('department_id', $department_ids)->where('type', 1);
                })->whereOr(function($query) use($admin_ids) {
                    $query->whereIn('admin_id', $admin_ids)->where('type', 2);
                });
            })
            ->select();
        }
        // echo SaleGoalsDetail::getLastSql();
    //    var_dump($department_ids, $admin_ids, collection($details)->toArray());
        $list = [];
        foreach ($department_ids as $k => $v) {
            $detaiinfo = array_filter($details, function($item) use($v) {
                return $item['department_id'] == $v && $item['type'] == 1;
            });
            if (empty($detaiinfo)) {
                $list[] = [
                    'salegoal_id' => $id,
                    'year' => $year,
                    'model_class' => $row['model_class'],
                    'type' => 1,
                    'department_id' => $v,
                    'month_1' => 0,
                    'month_2' => 0,
                    'month_3' => 0,
                    'month_4' => 0,
                    'month_5' => 0,
                    'month_6' => 0,
                    'month_7' => 0,
                    'month_8' => 0,
                    'month_9' => 0,
                    'month_10' => 0,
                    'month_11' => 0,
                    'month_12' => 0,
                    'yeartarget' => 0,
                ];
            } else {
                $list[] = array_values($detaiinfo)[0];
            }
        }
        foreach ($admin_ids as $k => $v) {
            $detaiinfo = array_filter($details, function($item) use($v, $department_id) {
                return $item['department_id'] == $department_id && $item['admin_id'] == $v && $item['type'] == 2;
            });
            if (empty($detaiinfo)) {
                $list[] = [
                    'salegoal_id' => $id,
                    'year' => $year,
                    'model_class' => $row['model_class'],
                    'type' => 2,
                    'department_id' => $department_id,
                    'admin_id' => $v,
                    'month_1' => 0,
                    'month_2' => 0,
                    'month_3' => 0,
                    'month_4' => 0,
                    'month_5' => 0,
                    'month_6' => 0,
                    'month_7' => 0,
                    'month_8' => 0,
                    'month_9' => 0,
                    'month_10' => 0,
                    'month_11' => 0,
                    'month_12' => 0,
                    'yeartarget' => 0,
                ];
            } else {
                $list[] = array_values($detaiinfo)[0];
            }
        }
        $result = array("total" => count($list), "data" => $list);
        return json($result);
    }

}
